<template>
  <div class="m-2.5 p-2.5 bg-white">
    <div>
      <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="联表条件" name="0" />
        <el-tab-pane label="查询条件" name="1" />
      </el-tabs>
      <div>
        <div v-show="activeName === '0'">
          <el-form :model="form" label-width="100px">
            <div class="grid grid-cols-2">
              <el-form-item label="选择数据库" prop="dsId">
                <el-select v-model="form.dsId" @change="haneleBaseChange" placeholder="请选择">
                  <el-option
                    v-for="(ds, index) in dsList"
                    :key="index"
                    :label="ds.name"
                    :value="ds.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item />
              <el-form-item label="主表" prop="queryTables[0].tbId">
                <el-select
                  v-model="queryTables[0].tbId"
                  @change="(val) => haneleTbChange(val, 0)"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(ds, index) in tbList"
                    :key="index"
                    :label="ds.code + '(' + ds.label + ')'"
                    :value="ds.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="从表" prop="queryTables[1].tbId">
                <el-select
                  v-model="queryTables[1].tbId"
                  @change="(val) => haneleTbChange(val, 1)"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(ds, index) in tbList"
                    :key="index"
                    :label="ds.code + '(' + ds.label + ')'"
                    :value="ds.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="主表字段" prop="joinItems[0].fromClId">
                <el-select
                  v-model="joinItems[0].fromClId"
                  @change="(val) => haneleClChange(val, 'from', 0)"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(ds, index) in fromClList"
                    :key="index"
                    :label="ds.comment + '(' + ds.name + ')'"
                    :value="ds.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="从表字段" prop="joinItems[0].toClId">
                <el-select
                  v-model="joinItems[0].toClId"
                  @change="(val) => haneleClChange(val, 'to', 0)"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(ds, index) in toClList"
                    :key="index"
                    :label="ds.comment + '(' + ds.name + ')'"
                    :value="ds.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleQuery">查询</el-button>
              </el-form-item>
            </div>
          </el-form>
        </div>
        <div v-show="activeName === '1'">
          <query-form
            v-model:queryField="queryField"
            :fieldList="qFieldList"
            @search="handleSearchQuery"
            @reset="restQuery"
          />
        </div>
      </div>
    </div>
    <div>
      <div class="my-2">
        <el-select
          style="width: 400px"
          v-model="checkedSelectedCols"
          @change="handleCheckedColsChange"
          placeholder="请选择要展示的列"
          multiple
          collapse-tags
          :max-collapse-tags="1"
        >
          <template #header>
            <div class="flex justify-between items-center">
              <el-checkbox
                v-model="checkAll"
                :indeterminate="isIndeterminate"
                @change="handleCheckAllChange"
              >
                全选
              </el-checkbox>
              <el-button @click="handleInvert">反选</el-button>
            </div>
          </template>
          <el-option v-for="cl in colOptions" :key="cl.keyId" :label="cl.label" :value="cl.keyId" />
        </el-select>
        <el-button class="ml-2" type="primary" @click="handleExport">导出表格 </el-button>
      </div>
      <el-table :data="tableData">
        <el-table-column
          v-for="(col, index) in tableCol"
          :key="index"
          :label="setTabelColLabel(col)"
          :prop="col.clAlias"
        />
      </el-table>
      <pagination
        v-show="tableTotal > 0"
        :total="tableTotal"
        v-model:page="pageParams.pageNum"
        v-model:limit="pageParams.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>
<script setup>
  import { ref, computed, watch } from 'vue';
  import { listSdkDqDs } from '@/api/web/db/dataquery/sdkDqDs';
  import { pageSdkDqChildCate } from '@/api/web/db/dataquery/sdkDqCate';
  import { listSdkDqDsTbCl } from '@/api/web/db/dataquery/sdkDqDsTbCl';

  import { pageSdkDqJoinQuery, exportSdkDqJoinQuery } from '@/api/web/db/dataquery/sdkDqQuery.js';
  import queryForm from './query-form.vue';

  const activeName = ref('0');
  const form = ref({
    dsId: null,
  });
  // 主从表数组
  const queryTables = ref([
    {
      tbId: null, //主表id
      tbName: null, // 主表名称
    },
    {
      tbId: null, // 从表id
      tbName: null, // 从表名称
    },
  ]);
  // 主从表所选字段
  const joinItems = ref([
    {
      fromTbId: null, // 主表id
      fromTbName: null, // 主表名称
      fromClId: null, // 主表字段id
      fromClName: null, // 主表字段名称id
      toTbId: null, // 从表id
      toTbName: null, // 从表名称
      toClId: null, // 从表字段id
      toClName: null, // 从表字段名称id
    },
  ]);

  // 搜索项 和 搜索参数
  const queryField = ref([]);

  // 筛选条件
  const conditions = ref([]);
  const dsList = ref([]);
  const tbList = ref([]);
  const fromClList = ref([]);
  const toClList = ref([]);

  const checkedSelectedCols = ref([]);
  const checkAll = ref(false);
  const isIndeterminate = ref(false);

  const pageParams = ref({
    pageNum: 1,
    pageSize: 10,
  });
  const tableData = ref([]);
  const tableCol = ref([]);
  const tableTotal = ref(0);

  watch(
    () => checkedSelectedCols.value,
    (val) => {
      if (val.length === 0) {
        checkAll.value = false;
        isIndeterminate.value = false;
      } else if (val.length === colOptions.value.length) {
        checkAll.value = true;
        isIndeterminate.value = false;
      } else {
        isIndeterminate.value = true;
      }
    },
  );
  // table 中的 中文
  const setTabelColLabel = computed(() => (col) => {
    const fIndex = queryTables.value.findIndex((item) => item.tbId === col.tbId);
    const str = fIndex === 0 ? '主表.' : fIndex === 1 ? '从表.' : '';
    return str + col.clComment + '(' + col.clName + ')';
  });
  // 根据表id 获取表name
  const getQueryTbName = computed(() => (tbId) => {
    return queryTables.value.find((tb) => tb.tbId === tbId)?.tbName;
  });

  // 列表显示 所勾选的字段
  const queryItems = computed({
    get() {
      return colOptions.value
        .filter((item) => {
          return checkedSelectedCols.value.includes(item.keyId);
        })
        .map((item) => {
          return {
            tbId: item.tbId, // 表id
            tbName: getQueryTbName.value(item.tbId), // 表名称
            clId: item.id, // 字段id
            clName: item.name, // 字段名称
          };
        });
    },
    set() {},
  });

  // 查询条件 col 列表
  const qFieldList = computed(() => {
    const queryTbLen = queryTables.value.length;

    if (queryTbLen === 2 && queryTables.value[0].tbId === queryTables.value[1].tbId) {
      return fromClList.value.map((item) => {
        return {
          ...item,
          keyId: item.id,
          tbName: getQueryTbName.value(item.tbId), // 表名称
          label: '主表.' + item.comment,
          tableCon: '主表',
        };
      });
    }
    return [
      ...fromClList.value.map((item) => {
        return {
          ...item,
          keyId: item.id + '主表.',
          tbName: getQueryTbName.value(item.tbId), // 表名称
          label: '主表.' + item.comment,
          tableCon: '主表',
        };
      }),
      ...toClList.value.map((item) => {
        return {
          ...item,
          keyId: item.id + '从表.',
          tbName: getQueryTbName.value(item.tbId), // 表名称
          label: '从表.' + item.comment,
          tableCon: '从表',
        };
      }),
    ];
  });
  const colOptions = computed(() => {
    const queryTbLen = queryTables.value.length;

    if (queryTbLen === 2 && queryTables.value[0].tbId === queryTables.value[1].tbId) {
      return fromClList.value.map((item) => {
        return {
          ...item,
          keyId: item.id,
          label: '主表.' + item.comment + '(' + item.name + ')',
        };
      });
    }
    return [
      ...fromClList.value.map((item) => {
        return {
          ...item,
          keyId: item.id + '主表.',
          label: '主表.' + item.comment + '(' + item.name + ')',
        };
      }),
      ...toClList.value.map((item) => {
        return {
          ...item,
          keyId: item.id + '从表.',
          label: '从表.' + item.comment + '(' + item.name + ')',
        };
      }),
    ];
  });
  function init() {
    getdsAll(); // 数据库列表
  }

  // 数据库列表
  async function getdsAll() {
    const res = await listSdkDqDs();
    console.log({ res });
    dsList.value = res?.data || [];
  }
  // 表 列表
  async function getTbAll(val) {
    if (!val) {
      tbList.value = [];
    }
    const params = { pid: val };
    const res = await pageSdkDqChildCate({}, params);
    console.log({ res });
    tbList.value = res?.data || [];
  }
  async function getClAll(val, arr) {
    const res = await listSdkDqDsTbCl({ tbId: val });
    const data = res?.data ?? [];
    arr.splice(0, arr.length, ...data);
  }

  // 数据库改变
  function haneleBaseChange(val) {
    // 清空联表条件
    queryTables.value = [
      {
        tbId: null, //主表id
        tbName: null, // 主表名称
      },
      {
        tbId: null, // 从表id
        tbName: null, // 从表名称
      },
    ];
    joinItems.value = [
      {
        fromTbId: null, // 主表id
        fromTbName: null, // 主表名称
        fromClId: null, // 主表字段id
        fromClName: null, // 主表字段名称
        toTbId: null, // 从表id
        toTbName: null, // 从表名称
        toClId: null, // 从表字段id
        toClName: null, // 从表字段名称
      },
    ];
    queryItems.value = [];
    // 清空查询条件
    conditions.value = [
      // {
      //   tbId: 10331, // 表id
      //   tbName: 'sys_logininfor', // 表名称
      //   clId: '16021', // 字段id
      //   field: 'info_id', // 字段名称
      //   oprType: 'eq',
      //   singleValue: 121,
      //   listValue: [],
      //   rangeValue: {
      //     from: '',
      //     to: '',
      //   },
      // },
    ];

    // 获取表数据
    getTbAll(val);
  }

  // 选择表 change 事件
  function haneleTbChange(val, type) {
    console.log('tbList', { val, type });
    const find = tbList.value.find((item) => item.id === val);
    queryTables.value[type].tbName = find?.code;
    console.log({ queryTables: queryTables.value });

    // 获取列数据
    if (type === 0) {
      getClAll(val, fromClList.value);
      joinItems.value.forEach((item) => {
        item.fromTbId = val;
        item.fromTbName = find?.code;
        item.fromClId = null; // 主表字段id
        item.fromClName = null; // 主表字段名称
      });
    } else if (type === 1) {
      getClAll(val, toClList.value);
      joinItems.value.forEach((item) => {
        item.toTbId = val;
        item.toTbName = find?.code;
        item.toClId = null; // 主表字段id
        item.toClName = null; // 主表字段名称
      });
    }
  }

  // 选择 列字段 change 事件
  function haneleClChange(val, type, index) {
    console.log('clList', { val, type });
    if (type === 'from') {
      const find = fromClList.value.find((item) => item.id === val);
      joinItems.value[index].fromClName = find?.name;
    } else if (type === 'to') {
      const find = toClList.value.find((item) => item.id === val);
      joinItems.value[index].toClName = find?.name;
    }
  }

  // 选择显示的字段 change 事件
  function handleCheckedColsChange(val) {
    console.log({ val, checkedSelectedCols: checkedSelectedCols.value });
    handleQuery();
  }

  // 全选 change 事件
  function handleCheckAllChange(val) {
    isIndeterminate.value = false;
    if (val) {
      checkedSelectedCols.value = [...colOptions.value.map((item) => item.keyId)];
    } else {
      checkedSelectedCols.value = [];
    }
    handleQuery();
  }
  // 反选 change 事件
  function handleInvert() {
    checkedSelectedCols.value = colOptions.value.reduce((pre, item) => {
      const keyId = item.keyId;
      if (checkedSelectedCols.value.includes(keyId)) return pre;
      pre.push(keyId);
      return pre;
    }, []);
    handleQuery();
  }

  // 查询条件
  function handleSearchQuery(params) {
    console.log({ params });
    conditions.value = params.conditions;
    handleQuery();
  }
  function restQuery() {
    // queryField.value = [];
    // pageParams.value.pageNum = 1;
    // getList();
  }

  // 获取列表
  function handleQuery() {
    pageParams.value.pageNum = 1;
    getList();
  }

  //
  async function getList() {
    const query = {
      ...form.value,
      queryTables: queryTables.value,
      joinItems: joinItems.value,
      queryItems: queryItems.value,
      conditions: conditions.value,
    };
    console.log({ query });
    const res = await pageSdkDqJoinQuery(pageParams.value, query).catch(() => {});
    console.log({ res });
    if (!res) {
      return;
    }
    const data = res.data;
    tableCol.value = data.queryItems;
    tableData.value = data?.page?.records || [];
    tableTotal.value = data?.page?.total || 0;
  }

  // 导出
  function handleExport() {
    const query = {
      ...form.value,
      queryTables: queryTables.value,
      joinItems: joinItems.value,
      queryItems: queryItems.value,
      conditions: conditions.value,
    };
    exportSdkDqJoinQuery(pageParams.value, query);
  }
  function handleClick() {}

  init();
</script>
<style lang="scss" scoped></style>
